#########################
#   Author : leilei.Qin #
#   Date : 2025/06/17   #
#   Id : SM2892         #
#########################

# 报表-折扣明细
from datetime import datetime
import pandas as pd
from dbResps import dc
from dbResps import storeId, Log
from bussinessApis import isNowDate
from collections import defaultdict
import json


def getQueryDiscountDetailReportFromDB(startTime: int, endTime: int):
    # 初始化字典用于汇总结果
    getQueryDiscountDetailReport = defaultdict(lambda: {'orderCount': 0, 'discountAmount': 0})
    # 查询order表
    orderTableName = 'order'
    orderColumns = "discount_info as discountInfo"
    orderWhere = f'store_id = "{storeId}" and `status` = \"SETTLED\" and (UNIX_TIMESTAMP(settle_time)*1000 between {startTime} and {endTime})'
    orderResp = dc.select(tableName=orderTableName, where=orderWhere, columns=orderColumns)

    # 初始化字典用于汇总结果
    getQueryDiscountDetailReport = defaultdict(lambda: {'orderCount': 0, 'discountAmount': 0})

    # 解析并汇总数据
    for record in orderResp:
        discount_info = json.loads(record['discountInfo'])
        for discount in discount_info:
            discountId = discount['discountId']
            getQueryDiscountDetailReport[discountId]['orderCount'] += 1
            getQueryDiscountDetailReport[discountId]['discountAmount'] += abs(discount['discountAmount']['amount'])

    # 转换为常规字典
    getQueryDiscountDetailReport = dict(getQueryDiscountDetailReport)

    return getQueryDiscountDetailReport

def getHistoryDiscountDetailFromDB(startTime: int, endTime: int):
    orderTableName = 'discount_detail_report_hour'
    startTime2Date = datetime.strptime(dc.timestamp2Data(startTime), "%Y/%m/%d %H:%M:%S").strftime('%Y-%m-%d %H:%M:%S')
    endTime2Date = datetime.strptime(dc.timestamp2Data(endTime), "%Y/%m/%d %H:%M:%S").strftime('%Y-%m-%d %H:%M:%S')
    where = f'store_id = "{storeId}" and report_day between "{startTime2Date}" and "{endTime2Date}"'
    orderResp = dc.select(tableName=orderTableName, where=where)
    df = pd.DataFrame(orderResp)
    getHistoryDiscountDetailReport = df.groupby(['discount_id']).agg(
        order_count=('order_count', 'sum'),
        discountAmount = ('discount_amount', 'sum')).reset_index()
    getHistoryDiscountDetailReport = {
        row['discount_id']: {'orderCount': row['order_count'], 'discountAmount': abs(row['discountAmount'])} for
        _, row in getHistoryDiscountDetailReport.iterrows()}
    return getHistoryDiscountDetailReport


# startTime = 1717434000000
# endTime = 1717606799000
# print(getHistoryDiscountDetailFromDB(startTime, endTime))